import axios from 'axios'

export default {
    namespaced: true,
    state: () => ({
        cart: []
    }),
    mutations: {
        updateCart(state, cart) {
            state.cart = cart
        },
        updateCartState(state, payload) {
            let index = state.cart.findIndex(item => item.id == payload.id)
            state.cart[index].goods_state = payload.value
        },
        updateCartCount(state, payload) {
            let index = state.cart.findIndex(item => item.id == payload.id)
            state.cart[index].goods_count = payload.value
        },
        updateAllState(state, val) {
            state.cart.forEach(item => item.goods_state = val)
        }
    },
    actions: {
        async getCartList(context) {
            const res = await axios.get('https://www.escook.cn/api/cart')
            context.commit('updateCart', res.data.list)
        }
    },
    getters: {
        allPrice(state) {
            return state.cart.filter(item => item.goods_state).reduce((sum, item) => sum += item.goods_count * item.goods_price, 0)
        },
        allCount(state) {
            return state.cart.filter(item => item.goods_state).reduce((sum, item) => sum += item.goods_count, 0)
        }
    }
}